package broadcaster

import (
	"golang.org/x/net/websocket"
	"fmt"
)
type client chan<- string

var (
	entering = make(chan client)
	leaving  = make(chan client)
	message  = make(chan string)
)

func Broadcaster() {
	clients := make(map[client]bool)
	for {
		select {
		case msg := <- message:
			for cli := range clients {
				cli <- msg
			}
		case cli := <- entering:
			clients[cli] = true
		case cli := <- leaving:
			delete(clients , cli)
			close(cli)
		}
	}
}

func HandleConn(conn *websocket.Conn , Is chan <- bool) {
	ch := make(chan string)
	go SendMessageToHttp(conn , ch)

	var who string
	who = conn.RemoteAddr().String()

	ch <- "You are" + who + "\n"
	message <- who + "are arrives"
	entering <- ch
	var xinxi string
	for {

		if err := websocket.Message.Receive(conn , &xinxi); err != nil {
			fmt.Errorf("ReverMessage error!\n")
			break
		} else {
			fmt.Printf("Message From Http : %s\n" , xinxi)
			message <- who + ":\n   " + xinxi + "\n"
		}
	}
	Is <- true
}
func SendMessageToHttp(conn *websocket.Conn , ch <- chan string) {
	for msg := range ch {
		conn.Write([]byte(msg))
	}
}